package mfuny.ggongal.admin.http;

import java.io.File;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.imageio.stream.FileImageOutputStream;

import mfuny.ggongal.admin.Message;
import mfuny.ggongal.admin.Server;
import mfuny.ggongal.admin.ad.AdDao;
import mfuny.ggongal.admin.ad.AdDetail;
import mfuny.ggongal.admin.ad.MissionDetail;
import mfuny.ggongal.admin.debug.Debug;
import mfuny.ggongal.admin.etc.EmailSender;
import mfuny.ggongal.admin.etc.Module;
import mfuny.ggongal.admin.exception.DifferentGgongException;
import mfuny.ggongal.admin.exception.MinusGgongException;
import mfuny.ggongal.admin.json.JsonCreater;
import mfuny.ggongal.admin.mygift.MyGiftService;
import mfuny.ggongal.admin.play.PlayService;
import mfuny.ggongal.admin.report.LoginDao;
import mfuny.ggongal.admin.users.UserDao;
import mfuny.ggongal.admin.users.UserService;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.ow2.util.base64.Base64;

import com.ibatis.sqlmap.client.SqlMapClient;

public class HttpUser {
	SqlMapClient sqlMapper;
	
	JsonCreater jc = new JsonCreater();
	MyGiftService mgs = new MyGiftService();
	HttpPostSender post = new HttpPostSender();
	
	public HttpUser() throws Exception {
		sqlMapper = Server.getSqlMapper( );
	}
	
	//회원가입.
//	@SuppressWarnings("unchecked")
//	public int user_insert(HashMap<String, String> map) throws Exception {
//		int result = 0;
//		int result2 = 0;
//		HashMap<String, Object> paramMap = new HashMap<String, Object>();
//		try {
//			sqlMapper.startTransaction( );
//			
//			//24시간 이내 가입 또는 탈퇴가 있는지 여부 판단.
//			int regCount = (Integer) sqlMapper.queryForObject("user_checkReg", map);
//			if(regCount > 0) {
//				return -1;
//			}
//			regCount = (Integer) sqlMapper.queryForObject("user_checkOut", map);
//			if(regCount > 0) {
//				return -1;
//			}
//			
//			//추천인 입력이 있는지 여부.
//			Object obj = map.get("recommend");
//			if(obj != null && !((String)obj).equals("") ) {
//				
//				result2 = user_idCheck( map.get( "recommend" ));		//유효 ID 여부.
//				if ( result2 > 0 ) {
//					paramMap.clear( );
//					paramMap.put( "id", map.get( "recommend" ) );
//					paramMap.put( "recommend_me", map.get( "id" ) );
//					result2 = sqlMapper.update( "user_setRecommend_me", paramMap );
//					if ( result2 <= 0 ) {
//						Debug.toDebugFile("recommend 오류");
//						throw new Exception();
//					}
//				}
//			}
//			
//			
//			result = sqlMapper.update( "user_insert", map );		//회원가입 처리(insert).
//			if(result > 0) {
//				//회원가입10000꽁 꽁내역등록.
//				paramMap.clear();
//				paramMap.put("id", map.get("id"));
//				paramMap.put("ggong", 10000);
//				paramMap.put("reason", "회원가입 축하기념");
////				int result3 = sqlMapper.update("myggong_insert", paramMap);
//				int result3 = (Integer)user_addGgongNoTrans(paramMap).get("responseCode");
//				if(result3 <= 0) {
//					Debug.toDebugFile("회원가입 10000꽁 꽁내역 등록 중 오류.");
//					throw new Exception();
//				}
//			}
//			
//			//추천인 등록 했을경우 추가 꽁.
//			if ( result2 > 0 ) {
//				paramMap.clear( );
//				List<String> ids = new ArrayList<String>();
//				ids.add( map.get( "id" ) );
//				ids.add( map.get( "recommend" ) );
//				paramMap.put( "ggong", 500 );
//				paramMap.put( "ids", ids );
//				result2 = sqlMapper.update( "user_addGgongs", paramMap );
//				if ( result2 <= 0 ) {
//					Debug.toDebugFile("가입자&추천인 꽁 추가 실패.");
//					throw new Exception();
//				}
//				
//				//가입자&추천인 꽁내역 추가.
//				List<HashMap<String, Object>> paramList = new ArrayList<HashMap<String, Object>>();
//				paramMap.clear();
//				paramMap.put("ggong", 500);
//				paramMap.put("id", map.get("id"));
//				paramMap.put("reason", "회원가입 추천인 등록");
//				paramList.add(paramMap);
//				
//				HashMap<String, Object> paramMap2 = (HashMap<String, Object>)paramMap.clone();
//				paramMap2.put("id", map.get("recommend"));
//				paramMap2.put("reason", "추천 받음");
//				paramList.add(paramMap2);
//				
//				HashMap<String, Object> parentMap = new HashMap<String, Object>();
//				parentMap.put("list", paramList);
//				
//				result2 = sqlMapper.update("myggong_inserts", parentMap);
//				if(result2 <= 0){
//					Debug.toDebugFile("가입자&추천인 꽁내역 등록 실패");
//					throw new Exception();
//				}
//				
//				//추천받은 사람의 총 추천수 확인.
//				int reCount = (Integer) sqlMapper.queryForObject("user_recommendMeCount", map.get("recommend"));
//				boolean giveBonus = true;
//				switch(reCount) {
//				case 5: paramMap2.put("ggong", 1000);
//					break;
//				case 10: paramMap2.put("ggong", 5000);
//					break;
//				case 15: paramMap2.put("ggong", 10000);
//					break;
//				case 20: paramMap2.put("ggong", 15000);
//					break;
//				case 30: paramMap2.put("ggong", 20000);
//					break;
//				case 50: paramMap2.put("ggong", 30000);
//					break;
//				default: giveBonus = false;
//				}
//				//해당 추천수를 받았을 경우 추가 꽁 지급.
//				if( giveBonus ) {
//					paramMap2.put("reason", reCount + "명 추천 받음");
//					user_addGgongNoTrans( paramMap2 );
//				}
//			}
//			
//			sqlMapper.commitTransaction( );
//		}catch(Exception e) {
//			Debug.toDebugFile(e, "user_insert");
//			result = 0;
//		} finally {
//			sqlMapper.endTransaction( );
//		}
//		
//		return result;
//	}
	
	//회원가입 db관리 꽁 지급용.
		@SuppressWarnings("unchecked")
		public JSONObject user_insert2(HashMap<String, String> map) throws Exception {
			JSONObject json = new JSONObject();
			int result = 0;
			int result2 = 0;
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			try {
				sqlMapper.startTransaction( );
				
				//번호가 없는경우.
				String pnum =  map.get("pnum");
				if( pnum == null || pnum.equals("") ) {
					json.put("responseCode", 0);
					return json;
				}
				
				//24시간 이내 가입 또는 탈퇴가 있는지 여부 판단.
				int regCount = (Integer) sqlMapper.queryForObject("user_checkReg", map);
				if(regCount > 0) {
					json.put("responseCode", -1);
					return json;
				}
				regCount = (Integer) sqlMapper.queryForObject("user_checkOut", map);
				if(regCount > 0) {
					json.put("responseCode", -1);
					return json;
				}
				
				//추천인 입력이 있는지 여부.
				Object obj = map.get("recommend");
				if(obj != null && !((String)obj).equals("") ) {
					
					result2 = user_idCheck( map.get( "recommend" ));		//유효 ID 여부.
					if ( result2 > 0 ) {
						paramMap.clear( );
						paramMap.put( "id", map.get( "recommend" ) );
						paramMap.put( "recommend_me", map.get( "id" ) );
						result2 = sqlMapper.update( "user_setRecommend_me", paramMap );
						if ( result2 <= 0 ) {
							Debug.toDebugFile("recommend 오류");
							throw new Exception();
						}
					}
				}
				
				
				result = sqlMapper.update( "user_insert", map );		//회원가입 처리(insert).
				if(result > 0) {
					
					//db 에서 꺼내온 꽁 지급.
					Object ggong = sqlMapper.queryForObject("gm_selectGgongByType", "user_join");
					if ( ggong == null ) {
						Debug.toDebugFile("DB에서 지급 꽁 가져오기 실패.");
						throw new Exception();
					}
					json.put("ggong", (Integer)ggong );
					paramMap.clear();
					paramMap.put("id", map.get("id"));
					paramMap.put("ggong", json.get("ggong") );
					paramMap.put("reason", "회원가입 축하기념");
//					int result3 = sqlMapper.update("myggong_insert", paramMap);
					int result3 = (Integer)user_addGgongNoTrans(paramMap).get("responseCode");
					if(result3 <= 0) {
						Debug.toDebugFile("회원가입 꽁내역 등록 중 오류.");
						throw new Exception();
					}
				}
				
				//추천인 등록 했을경우 추가 꽁.
				if ( result2 > 0 ) {
					paramMap.clear( );
					
					//gimasa 추천인 경우 특별 지급.
					int ggong = 0;
					if( ((String)obj).equals("gimasa") ) {
						ggong = 30000;
					} else {
						ggong = 500;
					}
					
					//가입자 꽁추가.
					paramMap.put("ggong", ggong);
					paramMap.put("id", map.get("id"));
					paramMap.put("reason", "회원가입 추천인 등록");
					result2 = (Integer)user_addGgongNoTrans(paramMap).get("responseCode");
					if( result2 <= 0 ) {
						Debug.toDebugFile("가입자 꽁 추가 실패.");
						throw new Exception();
					}
					
					//추천받은사람 꽁 추가.
					HashMap<String, Object> paramMap2 = (HashMap<String, Object>)paramMap.clone();
					paramMap2.put("ggong", 500);
					paramMap2.put("id", map.get("recommend"));
					paramMap2.put("reason", "추천 받음");
					result2 = (Integer)user_addGgongNoTrans(paramMap2).get("responseCode");
					if( result2 <= 0 ) {
						Debug.toDebugFile("추천받은 사람 꽁 추가 실패.");
						throw new Exception();
					}
					
					//추천받은 사람의 총 추천수 확인.
					int reCount = (Integer) sqlMapper.queryForObject("user_recommendMeCount", map.get("recommend"));
					boolean giveBonus = true;
					switch(reCount) {
					case 5: paramMap2.put("ggong", 1000);
						break;
					case 10: paramMap2.put("ggong", 5000);
						break;
					case 15: paramMap2.put("ggong", 10000);
						break;
					case 20: paramMap2.put("ggong", 15000);
						break;
					case 30: paramMap2.put("ggong", 20000);
						break;
					case 50: paramMap2.put("ggong", 30000);
						break;
					default: giveBonus = false;
					}
					//해당 추천수를 받았을 경우 추가 꽁 지급.
					if( giveBonus ) {
						paramMap2.put("reason", reCount + "명 추천 받음");
						user_addGgongNoTrans( paramMap2 );
					}
				}
				
				sqlMapper.commitTransaction( );
			}catch(Exception e) {
				Debug.toDebugFile(e, "user_insert");
				json.put("responseCode", 0);
				return json;
				
			} finally {
				sqlMapper.endTransaction( );
			}
			
			json.put("responseCode", result);
			return json;
		}
	
	//로그인 체크.
	@SuppressWarnings( "unchecked" )
	public JSONObject user_login(String id, String pw, String pnum, String pname, String pserial) throws Exception {
		JSONObject json = new JSONObject();
		int result = user_idCheck(id);
		if ( result > 0 ) {
			String dbPass = (String) sqlMapper.queryForObject( "user_selectPw", id );
			if ( dbPass.equals( pw )) {
				//아이디 비번 일치.
				result = 1;
				UserDao userDao = (UserDao) sqlMapper.queryForObject( "user_selectById", id );
				if(userDao.getStatus().equals("out")) {
					//탈퇴한 회원일 경우.
					json.put("responseCode", -2);
					return json;
				}
				
				//테스트용 인증 무시 아이디가 아닐경우.
				if( !id.equals("pppabab") &&
					!id.equals("eeppkkrr") &&
					!id.equals("qwerabcd") &&
					!id.equals("kakaka2000") &&
					!id.equals("ultima7") &&
					!id.equals("samsam5") &&
					!id.equals("coffee9") &&
					!id.equals("loststar") &&
					!id.equals("7eleven") &&
					!id.equals("sktfaker")	
						
						) {

					//기기 또는 번호가 변경되었는지 확인.
					if( !pnum.equals(userDao.getPnum()) || !pname.equals(userDao.getPname()) || !pserial.equals(userDao.getPserial()) ) {
						json.put("responseCode", -3);
						return json;
					}
					
				}
				
				
				//로그인 리포트.
				addLoginReport( userDao );
				
				//출석체크.
				setLogin_level(userDao);
				
				userDao = (UserDao) sqlMapper.queryForObject( "user_selectById", id );
				userDao.setPw( null );
				String regDate = new SimpleDateFormat("yyyy-MM-dd").format( userDao.getRegdate( ) );
				userDao.setRegdate( null );
				json = jc.getJson( userDao );
				json.put( "regdate", regDate );
				json.remove("outdate");
				json.remove("last_login");
				
			} else {
				//비번이 다름.
				result = -1;
			}
		}
		//아이디가 없으면 0
		json.put( "responseCode", result );
		return json;
	}
	
	//인증번호 발송.
	@SuppressWarnings("unchecked")
	public int requestPin(String pnum) throws Exception {
		HashMap<String, Object> smsInfo = (HashMap<String, Object>) sqlMapper.queryForObject("sms_selectInfo", null);
		String pinnumber = Module.shufflePin(6);
		String url = (String) smsInfo.get("url");
		HashMap<String, String> paramMap = new HashMap<String, String>();
		paramMap.put("cb", (String)smsInfo.get("ggong_pnum"));
		paramMap.put("ctn", pnum);
		paramMap.put("id", (String)smsInfo.get("id"));
		paramMap.put("pwd", (String)smsInfo.get("pwd"));
		paramMap.put("msgtype", "SMS");
		paramMap.put("text", "꽁알 본인 인증번호 [" + pinnumber + "]");
		paramMap.put("ukey", "ukey");
		paramMap.put("pinnumber", pinnumber);
		
		int count = (Integer) sqlMapper.queryForObject("pin_pnumCheck", pnum);
		int updateResult = sqlMapper.update( (count > 0 ? "pin_update" : "pin_insert"), paramMap);
		String smsResult = "";
		if( updateResult > 0 ) {
			paramMap.remove("pinnumber");
			smsResult = post.send( url, paramMap, "EUC-KR" );
			if( smsResult.indexOf("ERR") == 0 ) {
				return -1;
			}
		} else {
			return 0;
		}
		
		return 1;
	}
	
	//인증번호 확인.
	public int responsePin(String pnum, String pin) throws Exception {
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("pnum", pnum);
		paramMap.put("pin", pin);
		int result = (Integer)sqlMapper.queryForObject("pin_selectPinnumber", paramMap );
		
		return result;
	}
	
	//로그인시 인증번호 확인.
	@SuppressWarnings("unchecked")
	public JSONObject responsePinForLogin(HashMap<String, Object> params) throws Exception {
		JSONObject json = new JSONObject();
		int result = responsePin((String)params.get("pnum"), (String)params.get("pin"));
		if( result > 0 ) { 
			result = sqlMapper.update("user_phoneUpdateByPin", params);
			if( result <= 0 ) {
				json.put("responseCode", 0);
				return json;
			}
		} else {
			json.put("responseCode", 0);
			return json;
		}
		
		//유저정보 가져오기.
		UserDao userDao = (UserDao) sqlMapper.queryForObject( "user_selectById", params.get("id") );
		
		//로그인 리포트.
		addLoginReport( userDao );
		
		//출석체크.
		setLogin_level(userDao);
		
		//다시 최신정보 가져오기.
		userDao = (UserDao) sqlMapper.queryForObject( "user_selectById", params.get("id") );
		userDao.setPw( null );
		String regDate = new SimpleDateFormat("yyyy-MM-dd").format( userDao.getRegdate( ) );
		userDao.setRegdate( null );
		json = jc.getJson( userDao );
		json.put( "regdate", regDate );
		json.remove("outdate");
		json.remove("last_login");
		
		json.put("responseCode", 1);
		return json;
	}
	
	//로그인 후 스페셜게임 확인할 것 체크.
	@SuppressWarnings("unchecked")
	public JSONObject user_checkSpecial(String id) throws Exception {
		//당첨됐지만 받기를 누르지 않고 3일이상 지난거 안받기 처리(mygift 부분).
		try {
			sqlMapper.update("myGift_updateReceiveAfter3Days", id);
		}catch ( Exception e ) {}
		
		//경품게임 당첨 확인.
		List<Object> list = sqlMapper.queryForList("spec_checkIt", id);
		JSONObject json = new JSONObject();
		JSONArray mygiftArray = new JSONArray();
		
		if(list.size() > 0) {
			for(int i = 0; i < list.size(); i++) {
				HashMap<String, Object> map = (HashMap<String, Object>)list.get(i);
				if(spec_checkTime(map)) {
					//당첨.
					if(spec_isWin(map)) {
						int mygift_no = mgs.setMyGift(map, spec_getMyRank(map));
						HashMap<String, Object> mygift = (HashMap<String, Object>)sqlMapper.queryForObject("myGift_selectByNo2", mygift_no);
						mygift.put("myRank", spec_getMyRank(mygift));
						mygift.put("days", String.valueOf(mygift.get("days")));
						mygift.remove("needtax");
						mygift.remove("starttime");
						mygift.remove("endtime");
						mygift.remove("isreceived");
						mygiftArray.add(mygift);
					}
					//미당첨.
					else {
						int mygift_no = mgs.setMyGiftForFail(map);
						HashMap<String, Object> mygift = (HashMap<String, Object>)sqlMapper.queryForObject("myGift_selectByNo2", mygift_no);
						mygift.put("myRank", spec_getMyRank(mygift));
						mygift.put("days", String.valueOf(mygift.get("days")));
						mygift.put("iswin", 0);
//						mygift.put("name", "null");
//						mygift.put("price", "null");
						mygift.put("service", "special");
						mygift.put("img_savname", "null");
						mygift.remove("needtax");
						mygift.remove("starttime");
						mygift.remove("endtime");
						mygift.remove("isreceived");
						
						mygiftArray.add(mygift);
						
						sqlMapper.update("spec_update", (Integer)map.get("spec_no"));
					}
				}
			}
			
			if(mygiftArray.size() > 0) {
				json.put("responseCode", 1);
				json.put("mygift", mygiftArray);
			}else{
				json.put("responseCode", 0);
			}
			
		} else {
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//스페셜게임 체크 - 1시간 10분 이상 지났는지 여부.
	public boolean spec_checkTime(HashMap<String, Object> map) throws Exception {
		boolean check = false;
		Date nowDate = new Date();
		Date adTime = (Date)map.get("days");
		if(nowDate.getTime() - adTime.getTime() >= 259200000l) {
			sqlMapper.update("spec_update", (Integer)map.get("spec_no"));
		}
		else if(nowDate.getTime() - adTime.getTime() >= 11400000l ) {
			check = true;
		}
		return check;
	}
	
	//스페셜게임 체크 - 당첨 여부.
	public boolean spec_isWin(HashMap<String, Object> map) throws Exception {
		boolean isWin = false;
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", (Integer)map.get("ad_no"));
		
		int myRank = spec_getMyRank(map);
		List<Integer> winRankNumList = MissionDetail.getWinRankNum_mission(ad.getMission());
		for(int i = 0; i < winRankNumList.size(); i++) {
			if(winRankNumList.get(i) == myRank) {
				isWin = true;
			}
		}
		return isWin;
	}
	
	//스페셜게임 체크 - 나의 등수.
	@SuppressWarnings({ "unchecked" })
	public int spec_getMyRank(HashMap<String, Object> map) throws Exception {
		AdDao ad = (AdDao) sqlMapper.queryForObject("ad_selectNo", (Integer)map.get("ad_no"));
		Date starttime = AdDetail.ad_getDateForSGame(ad);
		
		map.put("starttime", starttime);
		map.put("score", MissionDetail.getScore_mission(ad.getMission()));
		map.put("id", (String)map.get("user_id"));
		if( starttime.getTime() >= AdDetail.vc27Date.getTime() ) {
			map.put("hour", AdDetail.vc27Hour);
			map.put("minute", AdDetail.vc27Minute);
		} else {
			map.put("hour", AdDetail.vc23Hour);
			map.put("minute", AdDetail.vc23Minute);
		}
		
		HashMap<String, Object> obj = (HashMap<String, Object>)sqlMapper.queryForObject("play_getRankByIdForSpecial27", map);
		Object rankObj = obj != null ? obj.get("rank") : 0;
		int myRank = 0;
		try {
			myRank = (int)(double)Double.parseDouble(rankObj.toString());
		} catch ( Exception e ) {	}
		
		return myRank;
	}
	
	//특정 광고(스페셜게임)의 당첨자 리스트 가져오기.
	public JSONObject user_getWinnerList(int ad_no, String days) throws Exception {
		Date date = Module.strToDate(days);
		List<Object> winnerList = new PlayService().getWinnerForAd(ad_no, date);
		JSONObject json = jc.getJsonByMapList(winnerList, "winnerList");
		return json;
	}
	
	//아이디 존재여부 확인.
	public int user_idCheck(String id) throws Exception {
		int result = (Integer)sqlMapper.queryForObject( "user_idCheck", id );
		return result;
	}
	
	//이메일 존재여부 확인.
	@SuppressWarnings("unchecked")
	public JSONObject user_emailCheck(String email) throws Exception {
		JSONObject json = new JSONObject();
		int result = (Integer) sqlMapper.queryForObject("user_emailCheck", email);
		if(result > 0) {
			json.put("responseCode", 1);
		}else{
			json.put("responseCode", 0);
		}
		return json;
	}
	
	//출석 처리.
	@SuppressWarnings("deprecation")
	public void setLogin_level(UserDao user) throws Exception {
		int lastDay = 7;		//연속출석 마지막 날.
		Date today = new Date();
		today.setHours(0);
		today.setMinutes(0);
		today.setSeconds(0);
		HashMap<String, Object> addGgongMap = new HashMap<String, Object>();
		HashMap<String, Object> addBonusMap = null;		//최종일 달성시 보너스 지급용.
		
		//라스트 로그인이 오늘이전이면 로그인레벨 변경 및 꽁 추가.
		if( today.getTime() > user.getLast_login().getTime() ) {
			Date yesterday = (Date)today.clone();
			yesterday.setDate( yesterday.getDate() - 1);
			//어제 이전이거나 연속출석 마지막 날이면 로그인레벨 초기화.
			if(yesterday.getTime() > user.getLast_login().getTime() || user.getLogin_level() == lastDay ) {
				user.setLogin_level(1);
			} else {
				user.setLogin_level( user.getLogin_level() + 1 );
				if( user.getLogin_level() == 7 ) {
					addBonusMap = new HashMap<String, Object>();
				}
			}
			try{
				sqlMapper.startTransaction();
				sqlMapper.update("user_setLogin_level", user);
				addGgongMap.put("id", user.getId());
				addGgongMap.put("ggong", (Integer)sqlMapper.queryForObject("lg_getGgong", user.getId()));
				addGgongMap.put("reason", "출석체크 " + user.getLogin_level() + "일째");
				
				if( addBonusMap != null ) {
					addBonusMap.put("id", user.getId());
					addBonusMap.put("ggong", (Integer)sqlMapper.queryForObject("lg_getLastGgong", null));
					addBonusMap.put("reason", "연속 출석");
				}
				user_addGgongNoTrans( addGgongMap );
				if( addBonusMap != null ) {
					user_addGgongNoTrans( addBonusMap );
				}
				sqlMapper.commitTransaction();
			}finally{
				sqlMapper.endTransaction();
			}
		}
		
		//라스트 로그인 업데이트.
		sqlMapper.update("user_updateLastLogin", user.getId());
	}
	
	//출석 현황 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getLogin_level(String id) throws Exception {
		JSONObject json = jc.getJsonByMap( (HashMap<String, Object>)sqlMapper.queryForObject("lg_getLogin_level", id)  );
		return json;
	}
	
	//특정 시간대 접속자수 증가.
	@SuppressWarnings("deprecation")
	public void addLoginReport( UserDao userClass ) throws Exception {
		try {
			sqlMapper.startTransaction( );
			
			LoginDao loginClass = new LoginDao();
			Timestamp ts = new Timestamp(System.currentTimeMillis( ));
			Method[] m = loginClass.getClass( ).getMethods( );
			String today = new SimpleDateFormat("yyyy-MM-dd").format( ts );
			
			int nowHour = ts.getHours( );
			for ( int i = 0; i < m.length; i++ ) {
				if ( m[i].getName( ).equals( "setH" + nowHour )) {
					m[i].invoke( loginClass, 1 );
				} 
			}
			loginClass.setDay( today );
			
			addLoginReportDetail( userClass, loginClass, "all");
			addLoginReportDetail( userClass, loginClass, "age");
			addLoginReportDetail( userClass, loginClass, "sex");
			addLoginReportDetail( userClass, loginClass, "job");
			addLoginReportDetail( userClass, loginClass, "area");
			addLoginReportDetail( userClass, loginClass, "marry");
			
			sqlMapper.commitTransaction( );
		} finally {
			sqlMapper.endTransaction( );
		}
	}
	
	//타겟별 접속자 수 증가처리.
	public void addLoginReportDetail(UserDao userClass, LoginDao loginClass, String targetType) throws Exception {
		if ( targetType.equals( "all" )) {
			loginClass.setT_type( targetType );
			loginClass.setT_value( targetType );
		} else if ( targetType.equals( "age" )) {
			loginClass.setT_type( targetType );
			loginClass.setT_value( UserService.getAges( userClass.getBirth_y( ) ) );
		} else {
			Method[] m = userClass.getClass( ).getMethods( );
			for ( int i = 0; i < m.length; i++ ) {
				if ( m[i].getName( ).toLowerCase( ).equals( "get" + targetType ) ) {
					loginClass.setT_type( targetType );
					loginClass.setT_value( (String)m[i].invoke( userClass ) );
				}
			}
		}
		if ( (Integer) sqlMapper.queryForObject( "login_selectToday", loginClass ) > 0 ) {
			sqlMapper.update( "login_update", loginClass );
		} else {
			sqlMapper.update( "login_insert", loginClass );
		}
	}
	
	//아이디 찾기.
	@SuppressWarnings("unchecked")
	public JSONObject idFind(String pnum, String email) throws Exception {
		JSONObject json = new JSONObject();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("pnum", pnum);
		paramMap.put("email", email);
		String id = (String) sqlMapper.queryForObject("user_findId", paramMap);
		if (id == null) {
			id = "0";
		}
		json.put("id", id);
		
		return json;
	}
	
	//비번 찾기.
	@SuppressWarnings("unchecked")
	public JSONObject pwFind(String id, String pnum, String email) throws Exception {
		JSONObject json = new JSONObject();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("pnum", pnum);
		paramMap.put("email", email);
		String pw = (String) sqlMapper.queryForObject("user_findPw", paramMap);
		if(pw != null) {
			//임시 비번 생성.
			pw = shufflePasswd(8);
			
			//db에 비번 업데이트.
			HashMap<String, Object> paramMap2 = new HashMap<String, Object>();
			paramMap2.put("pw", pw);
			paramMap2.put("id", id);
			sqlMapper.update("user_updatePw", paramMap2);
			
			//임시 비번 메일 보내기.
			new EmailSender().sendMail(
					"admin@ggongal.com", 
					email,
					"꽁알 - 임시 비밀번호 입니다.",
					
					"안녕하세요 꽁알입니다.<br/>" +
					"새로 변경된 비밀번호 안내.<br/>" +
					"[  " + pw + "  ]<br/><br/>" +
					"비밀번호는 빠른 시일내로 변경하시기 바랍니다."
					);
			
		} else {
			pw = "0";
		}
		json.put("pw", pw);
		return json;
	}
	
	//비번 체크.
	@SuppressWarnings("unchecked")
	public JSONObject user_pwCheck(String id, String pw) throws Exception {
		JSONObject json = new JSONObject();
		String pwDb = (String) sqlMapper.queryForObject("user_pwCheck", id);
		if (pw.equals(pwDb)) {
			json.put("responseCode", 1);
		} else {
			json.put("responseCode", 0);
		}
		return json;
	}
	
	//비번 변경.
	@SuppressWarnings("unchecked")
	public JSONObject user_pwUpdate(String id, String pw) throws Exception {
		JSONObject json = new JSONObject();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("pw", pw);
		int result = sqlMapper.update("user_updatePw", paramMap);
		json.put("responseCode", result);
		return json;
	}
	
	//개인정보변경.
	@SuppressWarnings("unchecked")
	public JSONObject user_infoUpdate(HashMap<String, Object> params) throws Exception {
		JSONObject json = new JSONObject();
		UserDao beforeInfo = (UserDao) sqlMapper.queryForObject("user_selectByIdMap", params);
		int result = 0;
		try {
			sqlMapper.startTransaction();
			
			if(params.get("recommend") != null && !params.get("recommend").equals("") ) {
				//본인 아이디를 추천하였을경우 오류처리.
				if( params.get("recommend").equals(params.get("id"))) {
					Debug.toDebugFile("recommend 오류 (아이디와 추천인 동일) / id : " + params.get("id") + " / recommend : " + params.get("recommend"));
					throw new Exception();
				}
				
				if(beforeInfo.getRecommend() == null || beforeInfo.getRecommend().equals("")) {
					//recommend_me 등록.
					HashMap<String, Object> params2 = new HashMap<String, Object>();
					params2.put("id", params.get("recommend"));
					params2.put("recommend_me", params.get("id"));
					result = sqlMapper.update("user_setRecommend_me", params2);
					if (result <= 0) {
						Debug.toDebugFile("recommend_me 오류");
						throw new Exception();
					}
					
					//추천인 등록 했을경우 추가 꽁. (버전코드 20 이후)
					if ( result > 0 ) {
						HashMap<String, Object> paramMap = new HashMap<String, Object>();
						Object obj = params.get("recommend");
						
						//gimasa 추천인 경우 특별 지급.
						int ggong = 0;
						if( ((String)obj).equals("gimasa") ) {
							ggong = 30000;
						} else {
							ggong = 500;
						}
						
						//가입자 꽁추가.
						paramMap.put("ggong", ggong);
						paramMap.put("id", params.get("id"));
						paramMap.put("reason", "회원가입 추천인 등록");
						result = (Integer)user_addGgongNoTrans(paramMap).get("responseCode");
						if( result <= 0 ) {
							Debug.toDebugFile("가입자 꽁 추가 실패.");
							throw new Exception();
						}
						
						//추천받은사람 꽁 추가.
						HashMap<String, Object> paramMap2 = (HashMap<String, Object>)paramMap.clone();
						paramMap2.put("ggong", 500);
						paramMap2.put("id", params.get("recommend"));
						paramMap2.put("reason", "추천 받음");
						result = (Integer)user_addGgongNoTrans(paramMap2).get("responseCode");
						if( result <= 0 ) {
							Debug.toDebugFile("추천받은 사람 꽁 추가 실패.");
							throw new Exception();
						}
						
						// 추천받은 사람의 총 추천수 확인.
						int reCount = (Integer) sqlMapper.queryForObject("user_recommendMeCount",
								params.get("recommend"));
						boolean giveBonus = true;
						switch (reCount) {
						case 5:
							paramMap2.put("ggong", 1000);
							break;
						case 10:
							paramMap2.put("ggong", 5000);
							break;
						case 15:
							paramMap2.put("ggong", 10000);
							break;
						case 20:
							paramMap2.put("ggong", 15000);
							break;
						case 30:
							paramMap2.put("ggong", 20000);
							break;
						case 50:
							paramMap2.put("ggong", 30000);
							break;
						default:
							giveBonus = false;
						}
						// 해당 추천수를 받았을 경우 추가 꽁 지급.
						if (giveBonus) {
							paramMap2.put("reason", reCount + "명 추천 받음");
							user_addGgongNoTrans(paramMap2);
						}
					}
				} else {
					params.put("recommend", null);
				}
			} else {
				params.put("recommend", null);
			}
					
			result = sqlMapper.update("user_infoUpdate", params);
			json.put("responseCode", result);
			sqlMapper.commitTransaction();
			
		} catch(Exception e) {
			json.put("responseCode", 0);
			Debug.toDebugFile(e, "user_infoUpdate");
			
		} finally {
			sqlMapper.endTransaction();
		}
		
		return json;
	}
	
	//내 경품당첨 리스트.
	@SuppressWarnings("unchecked")
	public JSONObject user_getMyGifts(String id, int start, int type) throws Exception {
		String sqlId = "";
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("start", start);
		
		switch(type) {
		case 0:	//전체.
			sqlId = "myGift_selectMyGiftsAll";
			break;
		case 1:	//수령.
			sqlId = "myGift_selectMyGiftsTrue";
			break;
		case 2:	//취소.
			sqlId = "myGift_selectMyGiftsFalse";
			break;
		}
		
		JSONObject json = new JSONObject();
		List<Object> myGiftList = sqlMapper.queryForList(sqlId, paramMap);
		int count = (Integer)sqlMapper.queryForObject("myGift_selectMyGiftCount", id);
		
		if(myGiftList.size() > 0) {
			for(int i = 0; i < myGiftList.size(); i++) {
				HashMap<String, Object> map = (HashMap<String, Object>)myGiftList.get(i);
				map.put("days", map.get("days") + "");
				myGiftList.set(i, map);
			}
			json = jc.getJsonByMapList(myGiftList, "myGiftList");
			json.put("responseCode", 1);
		} else {
			json.put("responseCode", 0);
		}
		
		json.put("count", count);
		return json;
	}
	
	//배송지 입력.
	@SuppressWarnings("unchecked")
	public JSONObject user_setAddress(HashMap<String, String> params) throws Exception {
		JSONObject json = new JSONObject();
		int result = sqlMapper.update("user_addressUpdate", params);
		json.put("responseCode", result);
		return json;
	}
	
	//꽁 가감 처리.
	@SuppressWarnings("unchecked")
	public JSONObject user_addGgong(HashMap<String, Object> params) throws Exception {
		JSONObject json = new JSONObject();
		try{
			sqlMapper.startTransaction();
			int result = sqlMapper.update("user_addGgong", params);
			if( result <= 0 ) {
				throw new Exception("꽁 가감오류");
			}
			
			int ggong = (Integer)sqlMapper.queryForObject("user_selectGgong", (String)params.get("id"));
			if( ggong < 0 ) {
				throw new Exception("꽁 음수 오류");
			}
			
			//꽁내역 reason 한글 대체.
			String reason = "";
			try{
				int reason_i = Integer.parseInt((String)params.get("reason"));
				reason = Message.getAddGgong_msg(reason_i);
			}catch(Exception e) {
				reason = (String)params.get("reason");
			}
			params.put("reason", reason);
			result = sqlMapper.update("myggong_insert", params);
			if( result <= 0 ) {
				throw new Exception("나의 꽁내역 등록 오류");
			}
			
			json.put("responseCode", result);
			json.put("ggong", ggong);
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "user_addGgong");
			json.put("responseCode", 0);
		}finally{
			sqlMapper.endTransaction();
		}
		
		return json;
	}
	@SuppressWarnings("unchecked")
	public JSONObject user_addGgongNoTrans(HashMap<String, Object> params) throws Exception {
		JSONObject json = new JSONObject();
		try{
//			sqlMapper.startTransaction();
			int result = sqlMapper.update("user_addGgong", params);
			if ( result <= 0) {
				throw new Exception("꽁 가감 오류");
			}
			int ggong = (Integer)sqlMapper.queryForObject("user_selectGgong", (String)params.get("id"));
			if( ggong < 0 ) {
				throw new Exception("꽁 음수 오류");
			}
			
			//꽁내역 reason 한글 대체.
			String reason = "";
			try{
				int reason_i = Integer.parseInt((String)params.get("reason"));
				reason = Message.getAddGgong_msg(reason_i);
			}catch(Exception e) {
				reason = (String)params.get("reason");
			}
			params.put("reason", reason);
			result = sqlMapper.update("myggong_insert", params);
			if( result <= 0 ) {
				throw new Exception("나의 꽁내역 등록 오류");
			}
			
			json.put("responseCode", result);
			json.put("ggong", ggong);
			
//			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "user_addGgong");
			json.put("responseCode", 0);
		}
		
		return json;
	}
	//꽁 가감 처리(암호화 버전)(vc-24).
	@SuppressWarnings("unchecked")
	public JSONObject user_addGgong2(HashMap<String, Object> params)	throws Exception {
		JSONObject json = new JSONObject();
		try {
			sqlMapper.startTransaction();
			
			// 꽁내역 reason 한글 대체.
			String reason = "";
			try {
				int reason_i = Integer.parseInt( String.valueOf(params.get("reason")));
				reason = Message.getAddGgong_msg(reason_i);
			} catch (Exception e) {
				reason = String.valueOf(params.get("reason"));
			}
			params.put("reason", reason);
			
			//전 후 꽁 수치 확인용
			HashMap<String, Object> resultMap = (HashMap<String, Object>) sqlMapper.queryForObject("user_checkGgong", params);
			
			//현재 꽁 확인 & 음수 체크.
			if( (int)(double)Double.parseDouble(String.valueOf(params.get("nowGgong"))) != 
					(int)(double)Double.parseDouble(String.valueOf(resultMap.get("ggong"))) ) 
			{
				throw new DifferentGgongException("현재 꽁 다름 / id : " + params + " /서버 실제 꽁 : " + resultMap.get("ggong"));
			}
			if( (int)(double)Double.parseDouble(String.valueOf(resultMap.get("afterggong"))) < 0	) {
				throw new Exception("꽁 음수 / id : " + params + " /서버 실제 꽁 : " + resultMap.get("ggong"));
			}
			
			//꽁 가감처리.
			int result = sqlMapper.update("user_addGgong", params);
			if ( result <= 0) {
				throw new Exception("꽁 가감 오류");
			}
			
			//꽁 내역 등록.
			result = sqlMapper.update("myggong_insert", params);
			if( result <= 0 ) {
				throw new Exception("나의 꽁내역 등록 오류");
			}

			json.put("responseCode", 1);
			json.put("ggong", (int)(double)Double.parseDouble(String.valueOf(resultMap.get("afterggong"))));

			sqlMapper.commitTransaction();
			
		} catch ( DifferentGgongException e ) {
			//현재 꽁이 다를경우.
			Debug.toDebugFile(e, "user_addGgong2");
			json.put("responseCode", -2);
			
		} catch ( MinusGgongException e ) {
			//꽁이 음수가 될 경우.
//			Debug.toDebugFile(e, "user_addGgong2");
			json.put("responseCode", -1);
			
		} catch (Exception e) {
			//기타 오류.
			Debug.toDebugFile(e, "user_addGgong2");
			json.put("responseCode", 0);
			
		} finally {
			sqlMapper.endTransaction();
		}

		return json;
	}
		
	
	//꽁 내역 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getMyGgongList(String id, int start, String type) throws Exception {
		String sqlId = "myggong_selectById";
		
		if(type != null) {
			int type2 = Integer.parseInt(type);
			switch(type2) {
			case 0:
				sqlId = "myggong_selectById";
				break;
			case 1:
				sqlId = "myggong_selectById1";
				break;
			case 2:
				sqlId = "myggong_selectById2";
				break;
			}
		}
		
		JSONObject json = new JSONObject();
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("start", start);
		List<Object> myGgongList = sqlMapper.queryForList(sqlId, paramMap);
		int myGgong = (Integer)sqlMapper.queryForObject("user_selectGgong", id);
		for(int i = 0; i < myGgongList.size(); i++) {
			HashMap<String, Object> map = (HashMap<String, Object>) myGgongList.get(i);
			map.put("handledate", ""+map.get("handledate"));
			myGgongList.set(i, map);
		}
		
		if(myGgongList.size() > 0) {
			json = jc.getJsonByMapList(myGgongList, "myggong");
			json.put("responseCode", 1);
			json.put("myTotalGgong", myGgong);
			
		}else{
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//꽁 랭킹(글로벌) 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getGgongRank(String id, int start) throws Exception {
		List<Object> rankList = sqlMapper.queryForList("user_selectGgongRank", start);
		JSONObject json = null;
		if(rankList.size() > 0) {
			json = jc.getJsonByMapList(rankList, "ggongRank");
			json.put("responseCode", 1);
			json.put("myRank", sqlMapper.queryForObject("user_selectMyGgongRank", id));
			
		}else{
			json = new JSONObject();
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//경품 랭킹(글로벌) 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getGiftRank(String id, int start) throws Exception {
		List<Object> rankList = sqlMapper.queryForList("user_getGiftRank", start);
		JSONObject json = null;
		if(rankList.size() > 0) {
			json = jc.getJsonByMapList(rankList, "giftRank");
			json.put("responseCode", 1);
			json.put("myRank", sqlMapper.queryForObject("user_getMyGiftRank", id));
		} else {
			json = new JSONObject();
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//현재 꽁 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getGgong(String id) throws Exception {
		int ggong = (Integer)sqlMapper.queryForObject("user_selectGgong", id);
		JSONObject json = new JSONObject();
		json.put("ggong", ggong);
		return json;
	}
	
	//유저 연락처에서 친구 리스트 골라내서 꽁랭킹 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getMyFriends(String pnums) throws Exception {
		JSONObject json = new JSONObject();
		List<String> pnumList = new ArrayList<String>();
		String[] tempPnum = pnums.split(",");
		for(int i = 0; i < tempPnum.length; i++) {
			pnumList.add(tempPnum[i]);
		}
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("pnumList", pnumList);
		List<Object> myFriendsList = sqlMapper.queryForList("user_getMyFriends", paramMap);
		if(myFriendsList.size() > 0) {
			json = jc.getJsonByMapList(myFriendsList, "friendsList");
			json.put("responseCode", 1);
			
		}else{
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//연락처에서 친구목록 및 경품랭킹 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getMyFriendsGiftRank(String pnums) throws Exception {
		JSONObject json = new JSONObject();
		List<String> pnumList = new ArrayList<String>();
		String[] tempPnum = pnums.split(",");
		for(int i = 0; i < tempPnum.length; i++) {
			pnumList.add(tempPnum[i]);
		}
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("pnumList", pnumList);
		List<Object> myFriendsList = sqlMapper.queryForList("user_getMyFriendsGiftRank", paramMap);
		if(myFriendsList.size() > 0) {
			json = jc.getJsonByMapList(myFriendsList, "friendsList");
			json.put("responseCode", 1);
			
		}else{
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//내친구 꽁랭킹 가져오기.
	//현재 미사용.
	@SuppressWarnings("unchecked")
	public JSONObject user_getGgongRankByFriends(String friendsId) throws Exception {
		JSONObject json = new JSONObject();
		List<String> idList = new ArrayList<String>();
		String[] tempId = friendsId.split(",");
		for(int i = 0; i < tempId.length; i++) {
			idList.add(tempId[i]);
		}
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("idList", idList);
		List<Object> ggongRank = sqlMapper.queryForList("user_getGgongRankByFriends", paramMap);
		
		if(ggongRank.size() > 0) {
			json = jc.getJsonByMapList(ggongRank, "ggongRank");
			json.put("responseCode", 1);
		} else {
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//1:1 문의하기.
	@SuppressWarnings("unchecked")
	public JSONObject user_regAsk(HashMap<String, Object> params) throws Exception {
		if( params.get("subject") != null && params.get("subject").equals("") ) {
			params.put("subject", null);
		}
		int result = sqlMapper.update("ask_insert", params);
		JSONObject json = new JSONObject();
		if(result > 0) {
			json.put("responseCode", 1);
		}else{
			json.put("responseCode", 0);
		}
		return json;
	}
	
	//나의 1:1 문의 내역 가져오기.
	@SuppressWarnings("unchecked")
	public JSONObject user_getMyAskList(String id, int start) throws Exception {
		JSONObject json = null;
		HashMap<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		paramMap.put("start", start);
		List<Object> list = sqlMapper.queryForList("ask_selectMyAskList", paramMap);
		if(list.size() > 0) {
			json = jc.getJsonByMapList( list, "myAskList");
			json.put("responseCode", 1);
		} else {
			json = new JSONObject();
			json.put("responseCode", 0);
		}
		
		return json;
	}
	
	//사진 등록.
	@SuppressWarnings({ "unchecked", "null" })
	public JSONObject user_setMyPic(String id, String mypic) throws Exception {
		JSONObject json = new JSONObject();
		String fileName = Server.filePath + "mypic_" + id + ".jpg";
		FileImageOutputStream file = null;
		try{
			sqlMapper.startTransaction();
			
			//기존 파일이 있는경우 제거.
			File path = new File(fileName);
			if(path.isFile()) {
				path.delete();
			}
			
			//이미지 파일 저장.
			file = new FileImageOutputStream(path);
			byte[] b = Base64.decode(mypic.toCharArray());
			file.write(b, 0, b.length);
			file.close();
			
			//업로드 시간 db 저장.
			HashMap<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("id", id);
			paramMap.put("picupdate", String.valueOf(path.lastModified()));
			int result = sqlMapper.update("user_picupdate", paramMap);
			if(result <= 0) {
				throw new Exception("Picture update time error.");
			}
			
			json.put("responseCode", 1);
			
			sqlMapper.commitTransaction();
		}catch(Exception e){
			Debug.toDebugFile(e, "user_setMyPic");
			new File(fileName).delete();
			json.put("responseCode", 0);
		}finally{
			if(file == null) {
				file.close();
			}
			sqlMapper.endTransaction();
		}
		
		return json;
	}
	
	//유저 탈퇴처리.
	@SuppressWarnings("unchecked")
	public JSONObject user_out(HashMap<String, String> params) throws Exception {
		JSONObject json = new JSONObject();
		try {
			sqlMapper.startTransaction();
			int result = sqlMapper.update("user_out", params);
			if ( result > 0 ) {
				UserDao user = (UserDao) sqlMapper.queryForObject("user_selectById", params.get("id"));
				result = sqlMapper.update("user_outInsert", user);
			} else {
				throw new Exception("user_out 업데이트 처리 실패");
			}
			
			if ( result > 0 ) {
				result = sqlMapper.update("user_delete", params.get("id"));
			} else {
				throw new Exception("user_delete 실패");
			}
			
			json.put("responseCode", result);
			sqlMapper.commitTransaction();
			
		} catch (Exception e) {
			Debug.toDebugFile(e, "user_out");
			json.put("responseCode", 0);
		} finally {
			sqlMapper.endTransaction();
		}
		
		return json;
	}
	
	//우편번호 검색.
	@SuppressWarnings("unchecked")
	public JSONObject user_dongSearch(String dong) throws Exception {
		List<Object> zips = sqlMapper.queryForList("zip_dongSearch", dong);
		JSONObject json = jc.getJsonByMapList(zips, "dong");
		return json;
	}
	
	//임시 비번 생성기.
	public String shufflePasswd(int len) {
		char[] charSet = new char[] { '0', '1', '2', '3', '4', '5', '6', '7',
				'8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
				'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
				'w', 'x', 'y', 'z' };

		int idx = 0;
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < len; i++) {
			idx = (int) (charSet.length * Math.random());
			sb.append(charSet[idx]);
		}

		return sb.toString();
	}
}
